package com.library.common.wspoint.client;

import com.alibaba.fastjson2.JSON;
import com.library.common.utils.SecurityUtils;
import com.library.common.wspoint.WsDataInterface;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Package: com.library.common.wspoint.service
 * @ClassName: GlobalService
 * @Author: Yin
 * @Date: 10:59
 * @Description: 服务器上的 websocket 连接客户端
 */
@Slf4j
@Component
public class GlobalServerPointClient {

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Value("${devicews.host}")
    private String ip ;

    @Value("${devicews.port}")
    private int port ;

    private WebSocketClient client = null;

    @PostConstruct
    public void init() {
        client = new WebSocketClient(URI.create("ws://"+ip+":"+port+"/bookws/ws/device")) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                log.info("WebSocket客户端连接");
            }

            @Override
            public void onMessage(String s) {
                log.info("WebSocket客户端接收消息");
            }

            @Override
            public void onClose(int i, String s, boolean b) {
                log.info("WebSocket客户端连接关闭");
            }

            @Override
            public void onError(Exception e) {
                log.info("WebSocket客户端异常");
                e.printStackTrace();
            }
        };
        client.connect();
        // 重连
        threadPoolTaskExecutor.execute(() -> {
            while(true) {
                try {
                    TimeUnit.SECONDS.sleep(5);
                    if(client.isClosed()) {
                        log.info("WebSocket客户端连接关闭-尝试重连");
                        if(client.reconnectBlocking()) {
                            log.info("WebSocket客户端连接关闭-重连成功");
                        }
                    }
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 发送消息给服务器的websocket
     */
    public void send(WsDataInterface data) {
        try {
            // 发送
            client.send(JSON.toJSONString(data));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
